package com.example.myprojectoffeixue;

/**
 * Created by ASUS on 2016/11/18.
 */
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Message;
import android.text.InputFilter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.localization.Gateway;
import com.localization.GatewayRequestUtil;
import com.localization.SendUtil;
import com.localization.SocketCmdsDistribute;

import org.apache.http.entity.StringEntity;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author IdeasAndroid
 *         可展开（收缩）列表示例
 */
public class IdeasExpandableListAdapter extends BaseExpandableListAdapter {
    Dialog dialog;
    private Context mContext = null;
    private MyApplication m;
    private List<SheBeiClass> groupList;
    private List<List<SheBeiClass>> itemList ;
    private Dialog dialog1;
    Switch st;
    EditText et;
    public IdeasExpandableListAdapter(Context context, Dialog dialog1, List<SheBeiClass>groupList,List<List<SheBeiClass>>itemList) {
        this.mContext = context;
        this.dialog1 = dialog1;
        this.itemList=itemList;
        this.groupList=groupList;
        st= (Switch) mContext;
        m= (MyApplication) st.getApplication();
    }

    /**
     * 初始化数据，将相关数据放到List中，方便处理
     */


    public boolean areAllItemsEnabled() {
        return false;
    }

    /*
     * 设置子节点对象，在事件处理时返回的对象，可存放一些数据
     */
    public Object getChild(int groupPosition, int childPosition) {
        return itemList.get(groupPosition).get(childPosition);
    }

    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    /*
     * 字节点视图，这里我们显示一个文本对象
     */
    public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        ViewHolder h = null;
        if (convertView == null) {
            h = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(mContext);
            convertView = inflater.inflate(R.layout.item2, null);
            h.tv = (TextView) convertView.findViewById(R.id.tv_listview);
            h.iv = (ImageView) convertView.findViewById(R.id.iv_listview);
            h.iv1 = (ImageView) convertView.findViewById(R.id.iv1_listview);
            convertView.setTag(h);
        } else {
            h = (ViewHolder) convertView.getTag();
        }

        convertView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setTitle("重命名");
                builder.setIcon(android.R.drawable.ic_dialog_info);
                et = new EditText(mContext);
                et.setFilters(new InputFilter[]{new InputFilter.LengthFilter(5)});
                et.setHint("请输入新的设备名字");
                builder.setView(et);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        final String name = et.getText().toString();
                        Kuaiguanutil k = new Kuaiguanutil();
                        k.ieee = itemList.get(groupPosition).get(childPosition).ieee;
                        k.port = itemList.get(groupPosition).get(childPosition).port;
                        k.deviceId = itemList.get(groupPosition).get(childPosition).deviceId;
                        k.deviceName = name;
                        k.mac = itemList.get(groupPosition).get(childPosition).mac;
                        String l2 = JSON.toJSONString(k);
                        Log.d("l2", l2);
                        l2 = AESUtil.encrypt(l2);
                        Log.d("l2", l2);
                        HttpUtils httpUtils = new HttpUtils();
                        RequestParams params = new RequestParams();
                        params.setHeader("Content-Type", "application/json");
                        try {
                            params.setBodyEntity(new StringEntity(l2, "utf-8"));
                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                        httpUtils.send(HttpRequest.HttpMethod.POST, HttpConnection.renameDevice, params,
                                new RequestCallBack<String>() {

                                    @Override
                                    public void onFailure(HttpException arg0, String arg1) {
                                        HttpConnection.toastLog("网络异常", mContext);


                                    }

                                    @Override
                                    public void onSuccess(ResponseInfo<String> arg0) {
                                        if (arg0.result != null && !("".equals(arg0.result))) {
                                            arg0.result = AESUtil.decrypt(arg0.result);
                                            GateWay Gw2 = JSON.parseObject(arg0.result, GateWay.class);
                                            if (0 == Gw2.status) {
                                                itemList.get(groupPosition).get(childPosition).deviceName = name;
                                                IdeasExpandableListAdapter.this.notifyDataSetChanged();
                                            } else {
                                                HttpConnection.toastLog("修改失败", mContext);
                                            }

                                        } else {
                                            HttpConnection.toastLog("服务器错误", mContext);

                                        }
                                    }

                                });

                    }
                });
                builder.setNegativeButton("取消", null);
                AlertDialog dialog = builder.create();
                dialog.show();


                return true;
            }
        });
        // 获取子节点要显示的名称
        String name = itemList.get(groupPosition).get(childPosition).deviceName;

        // 设置文本视图的相关属性
        if (name != null) {
            h.tv.setText(name);
        } else {
            h.tv.setText("墙面开关");
        }
        if ("01".equals(itemList.get(groupPosition).get(childPosition).status)) {
            h.iv.setImageResource(R.drawable.kai);
            h.iv1.setImageResource(R.drawable.anguan);
        } else if ("00".equals(itemList.get(groupPosition).get(childPosition).status)) {
            h.iv.setImageResource(R.drawable.guan);
            h.iv1.setImageResource(R.drawable.ankai);
        }

        h.iv1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Log.d("SOCKET", SocketCmdsDistribute.m2_gateway.size()+"");
                if(Gateway.MacSocke.containsKey(itemList.get(groupPosition).get(childPosition).mac)) {
                    Log.d("走内网","内网");
                    if (itemList.get(groupPosition).size() != 0) {
                        String s = itemList.get(groupPosition).get(childPosition).status;
                        String ieee = itemList.get(groupPosition).get(childPosition).ieee;
                        String port = itemList.get(groupPosition).get(childPosition).port;
                        String mac = itemList.get(groupPosition).get(childPosition).mac;
                        Log.d("设备的网关",mac);
                        if ("00".equals(s)) {
                            s = "01";
                        } else {
                            s = "00";
                        }
                       String cmd=GatewayRequestUtil.createSwitchOnOffStr(mac,ieee,port,s);
                        Log.d("我发的命令",cmd);
                        SendUtil.Mac=mac;
                        SendUtil.cmd=cmd;
                        SendUtil.hand.sendEmptyMessage(0);
                    }
                }else {
                if (itemList.get(groupPosition).size() != 0) {
                    String s = itemList.get(groupPosition).get(childPosition).status;
                    String ieee = itemList.get(groupPosition).get(childPosition).ieee;
                    String port = itemList.get(groupPosition).get(childPosition).port;
                    String mac = itemList.get(groupPosition).get(childPosition).mac;
                    if ("00".equals(s)) {
                        s = "01";
                    } else {
                        s = "00";
                    }
                    Kuaiguanutil k = new Kuaiguanutil();
                    k.cmd = "1007";
                    k.ieee = ieee;
                    k.port = port;
                    k.status = s;
                    k.mac = mac;
                    String j = JSON.toJSONString(k);
                    Log.d("cmd", j);
                    //wsc.sendTextMessage(j);
                    if (m.flag3) {
                        m.c.send(j);
                        dialog1.show();
                        new Thread() {

                            @Override
                            public void run() {
                                for (int i = 0; i < 10; i++) {
                                    if (st.flag) {
                                        try {
                                            if (!dialog1.isShowing()) {
                                                return;
                                            }
                                            sleep(500);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                    } else {
                                        return;
                                    }
                                }
                                m.hand.sendEmptyMessage(55);
                                super.run();
                            }
                        }.start();
                    }else{
                        ToastUtils.showToast(mContext,"与后台服务器连接断开，正在重连");
                    }

                }}
            }
        });
        return convertView;
    }


    /*
     * 返回当前分组的字节点个数
     */
    public int getChildrenCount(int groupPosition) {
        return itemList.get(groupPosition).size();
    }

    /*
     * 返回分组对象，用于一些数据传递，在事件处理时可直接取得和分组相关的数据
     */
    public Object getGroup(int groupPosition) {
        return groupList.get(groupPosition);
    }

    /*
     * 分组的个数
     */
    public int getGroupCount() {
        return groupList.size();
    }

    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    /*
     * 分组视图，这里也是一个文本视图
     */
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater inflater = LayoutInflater.from(mContext);
            convertView = inflater.inflate(R.layout.member_listview, null);
        }
        ImageView iv = (ImageView) convertView.findViewById(R.id.tubiao);
        TextView text = (TextView) convertView.findViewById(R.id.content_001);
        String name = (String) groupList.get(groupPosition).deviceName;
        if (name != null) {
            text.setText(name);
        } else {
            text.setText("墙面开关");
        }


        if (isExpanded) {
            iv.setImageResource(R.drawable.button_xiajiantou);

        } else {

            iv.setImageResource(R.drawable.button_youjiantou);

        }
        return convertView;
    }

    /*
     * 判断分组是否为空，本示例中数据是固定的，所以不会为空，我们返回false
     * 如果数据来自数据库，网络时，可以把判断逻辑写到这个方法中，如果为空
     * 时返回true
     */
    public boolean isEmpty() {
        return false;
    }

    /*
     * 收缩列表时要处理的东西都放这儿
     */
    public void onGroupCollapsed(int groupPosition) {

    }

    /*
     * 展开列表时要处理的东西都放这儿
     */
    public void onGroupExpanded(int groupPosition) {

    }

    /*
     * Indicates whether the child and group IDs are stable across changes to
     * the underlying data.
     */
    public boolean hasStableIds() {
        return false;
    }

    /*
     * Whether the child at the specified position is selectable.
     */
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }


    class ViewHolder {

        TextView tv;
        ImageView iv;
        ImageView iv1;


    }















}
